﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VPSoftTestApplication.DAL;
using VPSoftTestApplication.Entity;
using VPSoftTestApplication.View;

namespace VPSoftTestApplication.Presenters
{
    public class MainViewPresenter
    {
        private IMainView _view;
        private AbstractDatabaseFactory _dataManager;

        public MainViewPresenter(IMainView view)
        {
            _view = view;
            _view.LoadInventors += LoadInventors;
            _dataManager = DatabaseFactory.GetInstance();
            //_dataManager.ConnectionString =
            //    @"Data Source=E:\work\Repository\VPSoftTestApplication\src\VPSoftTestApplication\DataBase\VPSoftTestDataBase1.sdf";

            //_view.SetDocumentHeaders = _dataManager.DocumentHeaderControler.List();
            _view.ChangeDatabase += ChangeDataBase;
            
            _view.DeleteInventory += DeleteRecord;
            _view.EditInventory += EditInventory;
            _view.AddInventory += AddInventory;
        }

        public void ChangeDataBase(object sender, EventArgs e)
        {
            _dataManager.ConnectionString = "Data Source="+_view.GetCurrentConnectionString;
            _view.SetDocumentHeaders = _dataManager.DocumentHeaderControler.List();
            LoadInventors(null,null);
        }

        public void LoadInventors (object sender, EventArgs e)
        {
            DocumentHeader documentHeader = _view.CurrentDocumentHeader;
            _view.CountPage = _dataManager.InventoryControler.ListCount(documentHeader, _view.PageSize);
            _view.SetInventories = _dataManager.InventoryControler.DocumentList(_view.CurrentDocumentHeader, _view.SortedColumn, _view.SortedType, (_view.Page - 1) * _view.PageSize, _view.PageSize);
        }

        public void AddInventory(object sender, EventArgs e)
        {
            Inventory inv = new Inventory();
            inv.DocumentHeaderIID = _view.CurrentDocumentHeader.IID;
            inv.CreateDate = DateTime.Now;
            if (new RecordView(inv).ShowDialog()== DialogResult.OK)
            {
                LoadInventors(null, null);
            }
        }
        

        public void EditInventory (object sender, EventArgs e)
        {
            if (new RecordView(_view.CurrentInventory).ShowDialog()== DialogResult.OK)
            {
                LoadInventors(null, null);
            }
        }

        public void DeleteRecord (object sender, EventArgs e)
        {
            _dataManager.InventoryControler.Delete(_view.CurrentInventory);
            LoadInventors(null, null);
        }
    }
}
